package com.bl.student.service.biz.purchase.impl;

import com.bl.student.dao.model.PurchaseEntity;
import com.bl.student.dao.model.UserEntity;
import com.bl.student.dao.repository.PurchaseRepository;
import com.bl.student.dao.repository.UserRepository;
import com.bl.student.service.biz.purchase.PurchaseService;
import com.bl.student.service.vo.purchase.PurchaseListVo;
import com.bl.student.service.vo.purchase.PurchaseManagerListVo;
import com.bl.student.service.vo.purchase.PurchaseManagerVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liangweikang on 18/1/30.
 */
@Service
@Log4j2
public class PurchaseServiceImpl implements PurchaseService{

    @Autowired
    PurchaseRepository purchaseRepository;

    @Autowired
    UserRepository userRepository;

    @Override
    public PurchaseListVo getPurchaseList(String uid, Pageable pageable) {
        PurchaseListVo purchaseListVo = new PurchaseListVo();

        Page<PurchaseEntity> purchaseEntities;

        purchaseEntities = purchaseRepository.findByUserIdEqualsOrderByCreateTime(uid,pageable);

        purchaseListVo.setTotalCount(purchaseEntities.getTotalElements());
        purchaseListVo.setList(purchaseEntities.getContent());

        return purchaseListVo;
    }

    @Override
    public PurchaseManagerListVo getPurchaseList(Pageable pageable) {
        PurchaseListVo purchaseListVo = new PurchaseListVo();

        List<PurchaseManagerVo> purchaseManagerListVos = new ArrayList<>();

        PurchaseManagerListVo purchaseManagerListVo = new PurchaseManagerListVo();

        Page<PurchaseEntity> purchaseEntities;

        purchaseEntities = purchaseRepository.findAllByOrderByCreateTimeDesc(pageable);

        for (PurchaseEntity purchaseEntity : purchaseEntities) {
            PurchaseManagerVo purchaseManagerVo = new PurchaseManagerVo();
            purchaseManagerVo.setPurchaseEntity(purchaseEntity);
            UserEntity userEntity = userRepository.findOne(purchaseEntity.getUserId());
            purchaseManagerVo.setUserEntity(userEntity);
            purchaseManagerListVos.add(purchaseManagerVo);
        }

        purchaseManagerListVo.setTotalCount(purchaseEntities.getTotalElements());
        purchaseManagerListVo.setList(purchaseManagerListVos);

        return purchaseManagerListVo;
    }
}
